<?php

namespace Home\Controller;

class TradeController extends HomeController
{
   // public function index($id =106,$userid =33)
    public function index($id ,$userid , $token)
    {

        $this->checkLog($userid, $token);
        //$_SESSION['userId'] =29;
        //查邮箱验证 ，实名认证 ，电话号码
//        $tradeData = M()->table('trade_trade as a')
//            ->field('a.id,a.userid,a.trade_id,a.order_id,a.status,a.price,a.num,a.pay_type,b.username,b.headimg,b.sm_is_ok,b.email_is_ok,c.trade_num,c.user_praise,c.user_trust')
//            ->join('left join trade_user as b on a.userid = b. id left join trade_user_credit as c on a.userid = c.userid')
//            ->where("a.id=" . $id)->select();
        $tradeData = M('Trade')->where(array(
            'id' => $id
        ))->find();

        // 1是发起订单的用户    2是发布广告的用户
        if ($userid == $tradeData['userid']) {
            $userData = M()->table('trade_trade as a')
                ->field('a.id,a.userid,a.trade_id,a.order_id,a.status,a.price,a.num,a.pay_type,b.personalnote,b.addtime,b.username,b.headimg,b.sm_is_ok,b.email_is_ok,c.first_tradetime,c.trade_num,c.user_praise,c.user_trust')
                ->join('left join trade_user as b on a.trade_id = b.id left join trade_user_credit as c on a.trade_id = c.userid')
                ->where("a.id=" . $id)->find();
            $userData['symbol'] = 1;
        }

        if ($userid == $tradeData['trade_id']) {
            $userData = M()->table('trade_trade as a')
                ->field('a.id,a.userid,a.trade_id,a.order_id,a.status,a.price,a.num,a.pay_type,b.personalnote,b.addtime,b.username,b.headimg,b.sm_is_ok,b.email_is_ok,c.first_tradetime,c.trade_num,c.user_praise,c.user_trust')
                ->join('left join trade_user as b on a.userid = b. id left join trade_user_credit as c on a.userid = c.userid')
                ->where("a.id=" . $id)->find();
            $userData['symbol'] = 2;
        }

        $this->ajaxReturn($userData, 'JSON');
    }

    //待收货
    public function waitRecive($id)
    {
        $tradePrice = M('Trade')->where('id =' . $id)->getField("price");
        $this->ajaxReturn($tradePrice, 'JSON');
    }


    //评价  usertype  1代码买家 2代码卖家
    public function evaluate($id , $user_praise , $userid , $token)
    {
        $this->checkLog($userid, $token);
        $tradeData = M('Trade')->where(array(
            'id' => $id
        ))->find();

        if ($tradeData['order_status'] == 1 || $tradeData['order_status'] == 2) {
            $this->ajaxError('订单还没付款不能评价');
        }

        if ($tradeData['order_status'] == 3) {
            $this->ajaxReturn('还没确认收到比特币，不能评价');
        }

        if ($tradeData['order_status'] == 5) {
            $this->ajaxError('不能重复评价');
        }


        //买家评价卖家
        if ($userid == $tradeData['userid']) {

            if ($tradeData['evaluatseller'] == 1) {
                $this->ajaxError('不能重复评价');
            }

            $creditData = M('UserCredit')->where('userid =' . $tradeData['trade_id'])->find();

            $trade_num = $creditData['trade_num'] + 1;

            $user_praise = ($creditData['user_praise'] + $user_praise * 20) / $creditData['praise_num'];

            $rs = M('UserCredit')->where(array(
                'userid' => $tradeData['trade_id']
            ))->save(array(
                'trade_num' => $trade_num,
                'user_praise' => $user_praise
            ));

            M('Trade')->where('id =' . $id)->setField("evaluatseller", 1);
        }
        if ($userid == $tradeData['trade_id']) {

            if ($tradeData['evaluatbuyer'] == 1) {
                $this->ajaxError('不能重复评价');
            }

            //评论买家
            $buyerId = M('Trade')->where(array(
                'id' => $id
            ))->getField("userid");

            $creditData = M('UserCredit')->where('userid =' . $buyerId)->find();

            $trade_num = $creditData['trade_num'] + 1;

            $praise = $creditData['praise_num'] +1;

            $user_praise = ($creditData['user_praise'] + $user_praise * 20) / $creditData['praise_num'];

            $rs = M('UserCredit')->where(array(
                'userid' => $buyerId
            ))->save(array(
                'trade_num' => $trade_num,
                'user_praise' => $user_praise,
                'praise' => $praise
            ));
            M('Trade')->where('id =' . $id)->setField("evaluatbuyer", 1);
        }

        if ($rs) {
            $this->ajaxSuccess('评论成功');
        } else {
            $this->ajaxError('评论失败');
        }
    }

    //标记已付款  id是订单id
    public function pay($id, $coin, $userid, $token)
    {
        $this->checkLog($userid, $token);
        //TODO 增加订单状态where  已修改
        $tradeData = M('Trade')->where('id=' . $id)->find();

        if ($tradeData['order_status'] == 0) {
            $this->ajaxError('交易已经关闭');
        }

        if ($tradeData['order_status'] == 3) {
            $this->ajaxError('已经支付成功');
        }

        if ($tradeData['deal'] > $tradeData['num']) {
            $this->ajaxError('已经成交,不能在支付');
        }
        if ($userid == $tradeData['userid']) {
            if ($tradeData['type'] == 1) {
                $rs = M('UserCredit')->where(array(
                    'userid' => $userid
                ))->setInc('trade_num' ,1);
                $first_trade = M('UserCredit')->where(array(
                    'userid' => $userid
                ))->getField('first_tradetime');

                if (!$first_trade) {
                    M('UserCredit')->where(array(
                        'userid' => $userid
                    ))->save(array(
                        'first_tradetime' => time()
                    ));
                }
            }
        }

        if ($userid == $tradeData['trade_id']) {
            if ($tradeData['type'] == 2) {
                $rs = M('UserCredit')->where(array(
                    'userid' => $userid
                ))->setInc('trade_num' ,1);
                if ($tradeData['type'] == 1) {
                    $first_trade = M('UserCredit')->where(array(
                        'userid' => $userid
                    ))->getField('first_tradetime');

                    if (!$first_trade) {
                        M('UserCredit')->where(array(
                            'userid' => $userid
                        ))->save(array(
                            'first_tradetime' => time()
                        ));
                    }
                }
            }
        }
        //$deal_num = $tradeData['num'] * $tradeData['price'];

        $m = M();
        // $m->execute('autocommit = 0');
        $m->execute('lock table trade_trade write , trade_user_coin write');

        if ($userid == $tradeData['userid']) {
            if ($tradeData['type'] == 1) {

                if ($tradeData['order_status'] != 1) {
                    $this->ajaxError('订单状态错误');
                }
                $rs[] = $m->table('trade_trade')->where('id=' . $id)->setField('order_status', 2);

            }

            if ($tradeData['type'] == 2) {
                //TODO 校验状态  已修改
                if (M('Trade')->where('id =' . $id)->getField('order_status') != 2) {
                    $this->ajaxError('对方还没标记付款');
                }

                $rs[] = $m->table('trade_user_coin')->where(array(
                    'userid' => $tradeData['trade_id']
                ))->setDec($coin . 'd', $tradeData['num']);

                $rs[] = $m->table('trade_user_coin')->where(array(
                    'userid' => $tradeData['userid']
                ))->setInc($coin, $tradeData['num']);

                $rs[] = $m->table('trade_trade')->where('id=' . $id)->setInc('deal', $tradeData['num']);

                $rs[] = $m->table('trade_trade')->where('id =' . $id)->save(array(
                    'order_status' => 3,
                    'status' => 2
                ));

            }

            if (check_arr($rs)) {
                $m->execute('commit');
                $m->execute('unlock tables');
                $arr = array(
                    'type' => 1,
                    'id' => $id,
                    'msg' => '付款OK'
                );
                $this->ajaxReturn($arr, 'JSON');
            } else {
                $m->execute('rollback');
                $m->execute('unlock tables');
                $this->ajaxError("付款失败");
            }
        }

        if ($userid == $tradeData['trade_id']) {

            if ($tradeData['type'] == 1) {

                if (M('Trade')->where('id =' . $id)->getField('order_status') != 2) {
                    $this->ajaxError('对方还没标记付款');
                }

                $rs[] = $m->table('trade_user_coin')->where(array(
                    'userid' => $tradeData['trade_id']
                ))->setDec($coin . 'd', $tradeData['num']);

                $rs[] = $m->table('trade_user_coin')->where(array(
                    'userid' => $tradeData['userid']
                ))->setInc($coin, $tradeData['num']);

                $rs[] = $m->table('trade_trade')->where('id=' . $id)->setInc('deal', $tradeData['num']);

                $rs[] = $m->table('trade_trade')->where('id=' . $id)->save(array(
                    'order_status' => 3,
                    'status' => 2
                ));

                //交易成功减掉广告剩余量
                $rs[] = $m->table('trade_adver')->where(array(
                    'id' => $tradeData['adver_id']
                ))->setDec('num' , $tradeData['num']);
            }

            if ($tradeData['type'] == 2) {

                if (M('Trade')->where('id =' . $id)->getField('order_status') != 1) {
                    $this->ajaxError('订单状态有错误');
                }
                $rs[] = $m->table('trade_trade')->where('id=' . $id)->setField('order_status', 2);

            }
            if (check_arr($rs)) {
                $m->execute('commit');
                $m->execute('unlock tables');
                $arr = array(
                    'type' => 1,
                    'id' => $id,
                    'msg' => '收款OK'
                );
                $this->ajaxReturn($arr, 'JSON');
            } else {
                $m->execute('rollback');
                $m->execute('unlock tables');
                $this->ajaxError("收款失败");
            }
        }



    }

    //关闭交易 id是订单的id
    public function closeTrade($id, $trade_type, $coin_type, $userid, $token)
    {
        //TODO 校验状态 已修改
        $tradeData = M('Trade')->where('id=' . $id)->find();

        $this->checkLog($userid, $token);

        if ($tradeData['order_status'] == 0) {
            $this->ajaxError('您的交易已经关闭');
        }

        $m = M();
        //$m->execute('autocommit = 0');
        $m->execute('lock table trade_trade write , trade_user_coin write ,  trade_adver write');

        if ($tradeData['type'] == 2) {
            $rs[] = $m->table('trade_user_coin')->where('userid=' . $tradeData['userid'])->setDec($coin_type . "d", $tradeData['num']);
            $rs[] = $m->table('trade_user_coin')->where('userid=' . $tradeData['userid'])->setInc($coin_type, $tradeData['num']);
        }

        $rs[] = $m->table('trade_trade')->where(array('id' => $id))->setField('order_status', 0);

        if ($tradeData['type'] == 1){
            $rs[] = $m->table('trade_adver')->where(array(
                'id' => $tradeData['adver_id']
            ))->setDec('numd' , $tradeData['num']);

            $rs[] = $m->table('trade_adver')->where(array(
                'id' => $tradeData['adver_id']
            ))->setInc('num' , $tradeData['num']);
        }

        if (check_arr($rs)) {
            $m->execute('commit');
            $m->execute('unlock tables');
            $arr = array(
                'type' => 1,
                'msg' => '关闭成功'
            );
            $this->ajaxReturn($arr, 'JSON');
        } else {
            $m->execute('rollback');
            $m->execute('unlock tables');
            $this->ajaxError("关闭失败");
        }
    }

    //确认收到比特币
    public function confirmRecive($id, $userid, $token)
    {
        $this->checkLog($userid, $token);

        $tradeData = M('Trade')->where('status >=1 and id =' .$id)->find();

        if (!$tradeData) {
            $this->ajaxError('没有这笔订单');
        }


        $rs = M('Trade')->where(array(
            'id' => $id,
        ))->setField('order_status', 4);

        if ($rs) {
            $this->ajaxSuccess('修改订单成功');
        } else {
            $this->ajaxError('修改订单失败');
        }


        //$m = M();
        //$m->execute('autocommit = 0');
        //$m->execute('lock table trade_trade write , trade_user_coin write');

//        if (userid() == $tradeData['userid']) {
//            if ($tradeData['type'] == 1) {
//                //TODO 校验状态  已修改
//                if ($tradeData['order_status'] != 1) {
//                    $this->ajaxError('订单状态错误');
//                }
//            }
//
//            if ($tradeData['type'] == 2) {
//                if (M('Trade')->where('id =' . $id)->getField('order_status') != 2) {
//                    $this->ajaxError('对方还没标记付款');
//                }
//
//                $rs[] = $m->table('trade_user_coin')->where(array(
//                    'userid' => $tradeData['trade_id']
//                ))->setDec($coin_type . 'd', $tradeData['num']);
//
//                $rs[] = $m->table('trade_user_coin')->where(array(
//                    'userid' => $tradeData['userid']
//                ))->setInc($coin_type, $tradeData['num']);
//
//                $rs[] = $m->table('trade_trade')->where('id=' . $id)->setInc('deal', $tradeData['num']);
//
//            }
//
//        }
//
//        if (userid() == $tradeData['trade_id']) {
//
//            if ($tradeData['type'] == 1) {
//
//                if (M('Trade')->where('id =' . $id)->getField('order_status') != 2) {
//                    $this->ajaxError('对方还没标记付款');
//                }
//
//                $rs[] = $m->table('trade_user_coin')->where(array(
//                    'userid' => $tradeData['trade_id']
//                ))->setDec($coin_type . 'd', $tradeData['num']);
//
//                $rs[] = $m->table('trade_user_coin')->where(array(
//                    'userid' => $tradeData['userid']
//                ))->setInc($coin_type, $tradeData['num']);
//
//                $rs[] = $m->table('trade_trade')->where('id=' . $id)->setInc('deal', $tradeData['num']);
//
//            }
//
//        }
//
//        if (check_arr($rs)) {
//            $m->execute('commit');
//            $m->execute('unlock tables');
//            $arr = array(
//                'type' => 1,
//                'msg' => '确认成功'
//            );
//            $rs = M('Trade')->where(array(
//                'id' => $id,
//            ))->setField('order_status', 4);
//            $this->ajaxReturn($arr, 'JSON');
//        } else {
//            $m->execute('rollback');
//            $m->execute('unlock tables');
//            $this->ajaxError("确认失败");
//        }
    }

    //申诉
    public function appeal($id , $userid , $token) {

        $this->checkLog($userid , $token);

        $tradeData = M('Trade')->where(array(
            'id' => $id
        ))->find();

        $rs = M('Appeal')->add(array(
            'order_id' => $id,
            'buyer_id' => $tradeData['userid'],
            'seller_id' => $tradeData['trade_id']
        ));

        if ($rs) {
            $this->ajaxSuccess('正在处理，请耐心等待');
        }else{
            $this->ajaxError('申诉失败');
        }
    }
}



